import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { StatisticCard } from '@ant-design/pro-card';
import { Image, Card } from 'antd';
import ProForm,
{
  ProFormRadio, ProFormDigit, ProFormText,
} from '@ant-design/pro-form';
import { useModel } from '@@/plugin-model/useModel';
import { formatBytes32String, formatEther } from 'ethers/lib/utils';
import { getDeposits, postDeposit } from '@/services/aqchain-antd/deposit';
import moment from 'moment';
import { getWithdraws, postWithdraw } from '@/services/aqchain-antd/withdraw';
import { utils } from 'ethers';

const columns: ProColumns<API.ModelsDeposit>[] = [
  {
    title: '序号',
    valueType: 'index',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    valueType:'dateTime',
  },
  {
    title: '订单编号',
    dataIndex: 'orderNo',
  },
  {
    title: '金额',
    dataIndex: 'amount',
    valueType: 'digit',
  },
  {
    title: '区块链交易哈希',
    dataIndex: 'txHash',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      0: '已创建',
      1: '已支付',
      2: '完成',
    },
  },
]

const depositColumns: ProColumns<API.ModelsDeposit>[] = [
  {
    title: '序号',
    valueType: 'index',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    valueType:'dateTime',
  },
  {
    title: '订单编号',
    dataIndex: 'orderNo',
  },
  {
    title: '金额',
    dataIndex: 'amount',
    valueType: 'digit',
  },
  {
    title: '区块链交易哈希',
    dataIndex: 'txHash',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      0: '已创建',
      1: '已支付',
      2: '完成',
    },
  },
]

const withdrawColumns: ProColumns<API.ModelsWithdraw>[] = [
  {
    title: '序号',
    valueType: 'index',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    valueType:'dateTime',
  },
  {
    title: '订单编号',
    render: (node, record) => {
      return moment(record.createdAt).format("YYYYMMDDHHmmss")+record.id;
    },
  },
  {
    title: '金额',
    dataIndex: 'amount',
    valueType: 'digit',
  },
  {
    title: '区块链交易哈希',
    dataIndex: 'txHash',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      0: '已创建',
      1: '已支付',
      2: '完成',
    },
  },
]

const MyAccount: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { provider, currentAccount,contracts:{exchangeContract} } = initialState!;

  const [tab, setTab] = useState<string>('tab1');
  const [balance, setBalance] = useState<string>('0');

  useEffect(() => {
    provider
      .getSigner()
      .getBalance()
      .then((balance) => {
        setBalance(formatEther(balance.toString()).toString());
      });
    return;
  }, [currentAccount]);

  const imgStyle = {
    display: 'block',
    width: 42,
    height: 42,
  };

  return (
    <PageContainer
      content={
        <StatisticCard.Group direction={'row'}>
          <StatisticCard
            statistic={{
              title: '账户地址：',
              value: currentAccount?.address,
            }}
          />
          <StatisticCard
            statistic={{
              title: '当前可用余额：',
              value: balance,
              icon: (
                <img
                  style={imgStyle}
                  src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*dr_0RKvVzVwAAAAAAAAAAABkARQnAQ"
                  alt="icon"
                />
              ),
            }}
          />
        </StatisticCard.Group>
      }
    >
      <ProCard
        tabs={{
          tabPosition: 'top',
          activeKey: tab,
          onChange: (key) => {
            setTab(key);
          },
        }}
      >
        <ProCard.TabPane key='tab1' tab='充值'>
          <ProCard bordered headerBordered>
            <ProCard colSpan='50%'>
              <ProForm<API.ModelsDepositPost>
              submitter={{
                resetButtonProps: {
                  style: {
                    // 隐藏重置按钮
                    display: 'none',
                  },
                },
              }}
              onFinish={async (values)=>{
                try {
                  values.address = await provider.getSigner().getAddress();
                  values.signature = await provider
                    .getSigner()
                    .signMessage('Deposit Operation Sign Message');
                  const { success, data } = await postDeposit(
                    {},
                    values,
                  );
                  if (success) {
                    const url = data?.url!;
                    window.location.replace(url);
                  }
                } catch (e) {
                  console.error(e);
                }
              }}
              >
                <ProFormRadio.Group
                  name='type'
                  label='支付方式'
                  options={[
                    {
                      label: '支付宝',
                      value: 'alipay',
                    },
                  ]}
                  radioType='button'
                  initialValue='alipay'
                />
                <ProFormDigit
                  name='amount'
                  label='金额'
                  width='md'
                />
              </ProForm>
            </ProCard>
            <ProCard>
              <div>
                <Image
                  width={500}
                  preview={false}
                  src='http://img95.699pic.com/photo/50052/5096.jpg_wh300.jpg'
                />
              </div>
              <div>
                <Card title='温馨提示' bordered={false} style={{ width: 300 }}>
                  <p>
                    1.目前只接受支付宝账户支付充值，充值情况可能会稍有延迟，请耐心等待
                  </p>
                  {/*<p>2.系统目前暂不支持提现功能</p>*/}
                </Card>
              </div>
            </ProCard>
          </ProCard>
        </ProCard.TabPane>
        <ProCard.TabPane key='tab2' tab='提现'>
          <ProCard bordered headerBordered>
            <ProCard colSpan='50%'>
              <ProForm<API.ModelsWithdrawPost>
                submitter={{
                  resetButtonProps: {
                    style: {
                      // 隐藏重置按钮
                      display: 'none',
                    },
                  },
                }}
                onFinish={async (values)=>{
                  try {
                    // 签名消息
                    values.address = await provider.getSigner().getAddress();
                    values.signature = await provider
                      .getSigner()
                      .signMessage('Withdraw Operation Sign Message');
                    // 创建提现订单
                    const { success, data } = await postWithdraw(
                      {},
                      values,
                    );
                    // 订单创建成功后调用合约
                    if (success) {
                      console.log(data)
                      const signer = await provider.getSigner();
                      const gasPrice = await provider.getGasPrice();
                      const nonce = await signer.getTransactionCount();
                      console.log(utils.parseEther(values.amount.toString()).toString());
                      const overrides = {
                        from: await signer.getAddress(),
                        gasPrice: gasPrice.toNumber(),
                        gasLimit: 5000000,
                        value: utils.parseEther(values.amount.toString()),
                        nonce: nonce,
                      };
                      const min = await exchangeContract.min()
                      console.log(min.toString())
                      console.log(formatBytes32String( "123" ))
                      await exchangeContract.connect(provider.getSigner()).callStatic.ethToCurrency(data?.orderNo,overrides);
                      // await exchangeContract.callStatic.ethToCurrency(data?.orderNo,overrides);
                      const tx = await exchangeContract
                        .connect(provider.getSigner())
                        .ethToCurrency(
                          data?.orderNo,
                          overrides,
                        );
                      await tx.wait();
                      window.location.reload();
                    }
                  } catch (e) {
                    console.error(e);
                  }
                }}
                initialValues={{alipayName:currentAccount?.alipayName,alipayID:currentAccount?.alipayID}}
              >
                <ProFormRadio.Group
                  name='type'
                  label='提现渠道'
                  options={[
                    {
                      label: '支付宝',
                      value: 'alipay',
                    },
                  ]}
                  radioType='button'
                  initialValue='alipay'
                />
                <ProFormText
                  name='alipayID'
                  label='支付宝账户'
                  width='md'
                />
                <ProFormText
                  name='alipayName'
                  label='支付宝账户名称'
                  width='md'
                />
                <ProFormDigit
                  name='amount'
                  label='金额'
                  width='md'
                  rules={[
                    {
                      validator: (_, value) =>
                        value<balance || !value
                          ? Promise.resolve()
                          : Promise.reject(new Error('账户余额不足')),
                    },
                  ]}
                />
              </ProForm>
            </ProCard>
            <ProCard>
              <div>
                <Image
                  width={500}
                  preview={false}
                  src='http://img95.699pic.com/photo/50052/5096.jpg_wh300.jpg'
                />
              </div>
              <div>
                <Card title='温馨提示' bordered={false} style={{ width: 300 }}>
                  <p>
                    1.目前只接受支付宝账户提现，提现情况可能会稍有延迟，请耐心等待
                  </p>
                  {/*<p>2.系统目前暂不支持提现功能</p>*/}
                </Card>
              </div>
            </ProCard>
          </ProCard>
        </ProCard.TabPane>
        <ProCard.TabPane key='tab3' tab='充值记录'>
          <ProTable
            rowKey="orderNo"
            columns={depositColumns}
            params={{
              accountAddress: currentAccount?.address!,
            }}
            request={(params) => getDeposits(params)}
            options={false}
          />
        </ProCard.TabPane>
        <ProCard.TabPane key='tab4' tab='提现记录'>
          <ProTable
            rowKey="orderNo"
            columns={withdrawColumns}
            params={{
              accountAddress: currentAccount?.address!,
            }}
            request={(params) => getWithdraws(params)}
            options={false}
          />
        </ProCard.TabPane>
      </ProCard>
    </PageContainer>
  );
};

export default MyAccount;
